<template>
  <div id="boxArea" ref="target" class="selectMonthBoxSquare clearFixed">
    <span v-if="required" class="dot">*</span>
    <!-- el-input输入框：readonly和clearable属性不能同时使用 -->
    <el-input
      v-model="inputValue"
      class="inputStyle"
      type="text"
      placeholder="请选择查询月份"
      readonly
      @focus="showBox = true"
    >
      <template #prefix>
        <i class="el-input__icon el-icon-date" />
      </template>
      <template #suffix>
        <!-- 清空图标：有内容的时候渲染出来，鼠标hover到input框的时候再显示出来（即：输入框有内容并且鼠标悬浮时显示该图标） -->
        <i
          v-if="showClear"
          class="el-input__icon el-icon-circle-close clearIconStyle"
          @click="resetMonth(true)"
        />
      </template>
    </el-input>
    <el-tooltip
      v-if="showTips"
      class="item"
      effect="dark"
      :content="inputValue"
      placement="top-start"
    >
      <!-- <el-button type="info" plain icon="el-icon-info" circle size="small"> </el-button> -->
      <i class="el-icon-info"></i>
    </el-tooltip>
    <span v-if="showSum" class="suffix"> 共:{{ resultTimes.length }}</span>
    <!-- 年份月份选择弹框 -->
    <div v-if="showBox" class="selectContentBox">
      <div class="contentArea">
        <!-- 年份 -->
        <div
          class="mounth mounth-wrap mounth-around"
          style="padding: 15px 0; border-bottom: 1px solid #e5e5e5"
        >
          <div class="cursor" style="width: 15%">
            <el-button
              :disabled="curIndex >= DateList.length - 1"
              icon="DArrowLeft"
              circle
              size="small"
              @click="reduceYear"
            ></el-button>
          </div>
          <div>{{ OneY }}年</div>

          <div class="cursor t-r" style="width: 15%">
            <el-button
              :disabled="curIndex <= 0"
              icon="DArrowRight"
              circle
              size="small"
              @click="addYear"
            ></el-button>
            <!-- <el-icon><DArrowRight /></el-icon> -->
          </div>
        </div>
        <!-- 月份 -->
        <div class="conterList">
          <div class="mounth mounth-wrap monthLeft">
            <div
              v-for="(item, index) in DateList[curIndex].queryTime"
              :key="index"
              :class="filterClass(item)"
            >
              <div class="selectOptions" @click="onSelect(item)">{{ monthMap[item] }}月</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 按钮 -->
      <div class="buttonBox t-r">
        <span class="suffix" style="margin-right: 10px"> (已选:{{ optTimes.length }})</span>
        <el-button class="buttonStyle" type="primary" @click.stop="handleSubmit">确定</el-button>
        <el-button class="buttonStyle" plain @click.stop="resetMonth(false)">重置</el-button>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'UMounthPicker'
}
</script>
<script setup>
import { onClickOutside } from '@vueuse/core'
import { defineProps, onMounted, onBeforeMount, ref, defineEmits, defineExpose } from 'vue'

const props = defineProps({
  // @xh专属注释
  // @name: v-model绑定的值
  // @params:
  // @des:
  value: {
    type: Array,
    default: () => []
  },

  // @xh专属注释
  // @name:获取 前多少年的数据  默认为 20
  // @params:
  // @des:
  yearlength: {
    type: Number,
    default: 20
  },

  // @xh专属注释
  // @name:是否 是必选  是的话 默认 当前月份必选
  // @params:
  // @des:
  required: {
    type: Boolean,
    default: false
  },
  // @xh专属注释
  // @name:是否显示提示图标
  // @params:
  // @des:
  showTips: {
    type: Boolean,
    default: false
  },
  // @xh专属注释
  // @name:是否显示总数
  // @params:
  // @des:
  showSum: {
    type: Boolean,
    default: false
  }
})

const DateList = ref([]) // 年份月份数组
const optTime = ref([]) // 月份选中结果数组
const OneY = ref('') // 当前年份
const curIndex = ref(0) // 当前年份下标值
const optTimes = ref([]) // 点击月份时的所有选中结果
const resultTimes = ref([]) // 点击“确定”按钮后的选择结果
const showBox = ref(false) // 是否显示月份选择弹框
const inputValue = ref('') // 输入框的绑定值
const showClear = ref(false) // 是否显示输入框右边的“清空”小图标
const monthMap = ref({
  // 月份显示为中文
  1: '一',
  2: '二',
  3: '三',
  4: '四',
  5: '五',
  6: '六',
  7: '七',
  8: '八',
  9: '九',
  10: '十',
  11: '十一',
  12: '十二'
}) // 输入框的绑定值
const defaultValue = ref([]) // 记录初始值

const emits = defineEmits(['update:value'])

onBeforeMount(() => {
  //
  init()
})

onMounted(() => {
  defaultValue.value = props.value
  initDetault()
})

const target = ref(null)

onClickOutside(target, (event) => {
  showBox.value = false
})

// @xh专属注释
// @name:判读是选中样式
// @params:
// @des:
const filterClass = (key) => {
  const labels = `${DateList.value[curIndex.value].TimeYear}-${key <= 9 ? `0${key}` : key}`
  const days = optTime.value[curIndex.value].queryTime
  if (days.indexOf(labels) > -1) {
    // 有
    return 'onSelect'
  } else {
    // 无
    return 'select'
  }
}

// @xh专属注释
// @name:
// @params:
// @des:选择时间回调
const onSelect = (key) => {
  const labels = `${DateList.value[curIndex.value].TimeYear}-${key <= 9 ? `0${key}` : key}`

  const days = optTime.value[curIndex.value].queryTime

  if (days.indexOf(labels) > -1) {
    // 反选
    const index = days.indexOf(labels)
    optTime.value[curIndex.value].queryTime.splice(index, 1)
  } else {
    // 添加
    optTime.value[curIndex.value].queryTime.push(labels)
  }
  // console.log('xh', optTime.value, labels, curIndex.value, days)
  // return
  // console.log(optTime.value, key)
  const arr = []
  for (const item in optTime.value) {
    if (optTime.value[item].queryTime && optTime.value[item].queryTime.length > 0) {
      arr.push(...optTime.value[item].queryTime)
    }
  }
  optTimes.value = arr
  inputValue.value = arr.join(',')
  console.log('xh', optTime.value)
}
// @xh专属注释
// @name:组件失去焦点触发 值校验
// @params:
// @des:
const out = () => {
  // console.log(123)

  // 判断当前选中月份与上次点击“确定”按钮时的选择结果是否一致
  const arr = [...resultTimes.value]
  const arr2 = [...optTime.value.values]
  const equalArr = arr.sort().toString() == arr2.sort().toString()

  // debugger
  if (!equalArr) {
    // 如果不一致（因为是多选，所以必须是点击了“确定”按钮后才能进行查询）：
    // 将选择结果恢复到上次点击“确定”按钮时的结果
    optTime.value.values = resultTimes.value
    // 将输入框的值恢复到上次点击“确定”按钮时的值
    inputValue.value = optTime.value.values.join(',')
    // 根据输入框是否有值来判断清空图标是否渲染
    showClear.value = inputValue.value != ''
    // 将月份选中结果恢复到上次点击“确定”按钮时的选中月份
    const _opt = resultTimes.value.map((v) => {
      return v.substring(0, 4)
    })
    for (const item in optTime.value) {
      optTime.value[item].queryTime = []
      _opt.map((items, indexs) => {
        if (items === optTime.value[item].TimeYear) {
          optTime.value[item].queryTime.push(resultTimes.value[indexs])
        }
      })
    }
  }
  showBox.value = false
  // 关
}
// @xh专属注释
// @name:默认值设置
// @params:
// @des:
const checkResult = (bool = false) => {
  if (props.required) {
    const date = new Date() // Sat Jul 06 2019 19:59:27 GMT+0800 (中国标准时间)
    // 获取当前年份：
    const year = date.getFullYear() // 2019
    // 获取当前月份：
    let month = date.getMonth() + 1 // 7

    month = month > 9 ? month : '0' + month
    const today = year + '-' + month // 2019-07-06
    optTimes.value = [today]

    resultTimes.value = [today]
    // 将输入框的值恢复到上次点击“确定”按钮时的值
    inputValue.value = today
    const _opt = resultTimes.value.map((v) => {
      return v.substring(0, 4)
    })
    // console.log('xh', _opt, optTime.value)
    for (const item in optTime.value) {
      optTime.value[item].queryTime = []
      _opt.map((items, indexs) => {
        if (items === optTime.value[item].TimeYear) {
          optTime.value[item].queryTime.push(resultTimes.value[indexs])
        }
      })
    }
  }
  if (bool) {
    // this.$emit('input', resultTimes.value)
    emits('update:value', resultTimes.value)
  }
}

// 初始化数据，获取前20年，然后循环 每一年里面都有12个月的 得到数组 opTime 和 DateList
const init = () => {
  const date = new Date() // Sat Jul 06 2019 19:59:27 GMT+0800 (中国标准时间)
  // 获取当前年份：
  const year = date.getFullYear() // 2019
  // 获取当前月份：
  const month = date.getMonth() + 1 // 7
  const _opt = []
  const _optTime = []
  const arr = new Array(12)
  const optDate = getDateList()
  // console.log('xh123123', optDate)
  optDate.map((item, index) => {
    // 月份选择时el-checkbox-group绑定的值
    _optTime[index] = {
      TimeYear: item,
      queryTime: []
    }
    // 给每一年份设置12个月份，el-checkbox初始化显示时使用
    _opt[index] = {
      TimeYear: item,
      queryTime: []
    }
    for (let i = 1; i <= arr.length; i++) {
      if (item !== year || month >= i) {
        _opt[index].queryTime.push(i)
      }
    }
  })
  // console.log('xh1223', _opt)
  optTime.value = _optTime
  DateList.value = _opt
}

// 获取近20年年份列表，倒序排列，最新一年在最前面
const getDateList = () => {
  const Dates = new Date()
  const year = Dates.getFullYear()
  OneY.value = year
  const optDate = []
  for (let i = year - props.yearlength; i <= year + props.yearlength; i++) {
    optDate.push(i)
    if (i === year) {
      curIndex.value = i - (year - props.yearlength)
    }
  }

  return optDate.reverse()
}

// @xh专属注释
// @name:初始化默认值设置
// @params:
// @des:
const initDetault = () => {
  const date = new Date() // Sat Jul 06 2019 19:59:27 GMT+0800 (中国标准时间)
  // 获取当前年份：
  const year = date.getFullYear() // 2019
  // 获取当前月份：
  let month = date.getMonth() + 1 // 7

  month = month > 9 ? month : '0' + month
  const today = year + '-' + month // 2019-07-06
  if (defaultValue.value && defaultValue.value.length > 0) {
    optTimes.value = [...defaultValue.value]
    resultTimes.value = [...defaultValue.value]
    inputValue.value = defaultValue.value.join(',')
    // this.$emit('input', [...defaultValue.value])
    emits('update:value', [...defaultValue.value])
  } else if (props.required) {
    optTimes.value = [today]

    resultTimes.value = [today]
    // 将输入框的值恢复到上次点击“确定”按钮时的值
    inputValue.value = today
    // this.$emit('input', [today])
    emits('update:value', [today])
  } else {
    // this.$emit('input', [])
    emits('update:value', [])
  }

  const _opt = resultTimes.value.map((v) => {
    return v.substring(0, 4)
  })
  // console.log('xh', _opt, optTime.value)

  const arr = [...optTime.value]
  console.log('arr', arr)
  for (const item in arr) {
    arr[item].queryTime = []
    _opt.map((items, indexs) => {
      if (items === arr[item].TimeYear) {
        arr[item].queryTime.push(resultTimes.value[indexs])
      }
    })
  }
  optTime.value = arr
}
// 确定
const handleSubmit = () => {
  // const _this = this
  // 更新输入框的值
  inputValue.value = optTimes.value.join(',')
  // 根据输入框是否有值来判断清空图标是否渲染
  showClear.value = inputValue.value !== ''
  // 将点击“确定”按钮的选择结果保存起来（该值将在哪里使用：在点击弹框以外区域关闭弹框时使用，mounted中）
  resultTimes.value = optTimes.value
  // console.log('xh12',resultTimes.value,resultTimes.value.length)
  // debugger
  // 关闭弹框
  showBox.value = false

  // 全部删除 则恢复默认
  // if (_this.inputValue == '') {
  //   _this.initDetault()
  // }

  // _this.$emit('input',resultTimes.value)
  // debugger
  emits('update:value', resultTimes.value)
  // debugger
}
// 重置
const resetMonth = (bool = false) => {
  // 将年份重置到当前年份
  const Dates = new Date()
  const year = Dates.getFullYear()
  OneY.value = year
  // 将已选择的月份清空
  optTimes.value = []
  for (const i in optTime.value) {
    optTime.value[i].queryTime = []
  }
  // 将输入框清空
  inputValue.value = ''
  // 根据输入框是否有值来判断清空图标是否渲染，此处必然不渲染
  showClear.value = false

  // 关闭月份选择弹框

  if (bool) {
    // 将点击“确定”按钮的选择结果清空
    resultTimes.value = []
    checkResult(true)
  } else {
    checkResult()
  }
}

// 左上角年份减少
const reduceYear = () => {
  // 如果已经是最后一年了，则年份不能再减少了
  if (curIndex.value === DateList.value.length - 1) return
  // 当前下标值+1，根据下标值获取年份值
  curIndex.value = curIndex.value + 1
  OneY.value = DateList.value[curIndex.value].TimeYear
}
// 右上角年份增加
const addYear = () => {
  // 如果已经是当前年份了，则年份不能再增加了
  if (curIndex.value === 0) return
  // 当前下标值-1，根据下标值获取年份值
  curIndex.value = curIndex.value - 1
  OneY.value = DateList.value[curIndex.value].TimeYear
}
</script>
<style lang="scss" scoped>
.selectMonthBoxSquare {
  // margin-top: 10px;
  width: 290px;
  padding-right: 40px;
  position: relative;
  display: flex;
  align-items: center;
  .dot {
    color: red;
    position: absolute;
    left: -15px;
    top: 0;
  }
  .mounth {
    display: flex;
    // justify-content: center;
    align-items: center;
  }
  .mounth-wrap {
    flex-wrap: wrap;
  }
  .mounth-around {
    justify-content: space-between;
  }
  .inputStyle {
    width: 290px;
  }
  .clearIconStyle {
    display: none;
    cursor: pointer;
  }
  .inputStyle:hover .clearIconStyle {
    display: block;
  }
  .selectContentBox {
    position: absolute;
    top: 45px;
    left: 0;
    z-index: 2021;
    background: #ffffff;
    border: 1px solid #e5e5e5;
    border-radius: 3px;

    .contentArea {
      width: 330px;
      text-align: center;
    }
  }
  .el-icon-info {
    color: #666;
    margin-left: 10px;
    cursor: pointer;
  }
  .conterList {
    .select {
      width: 25% !important;
      margin: 20px 0 !important;
      text-align: center;

      transition: all 0.3s ease-in-out;
      .selectOptions {
        cursor: pointer;
        height: 40px;
        // background: #4ca8ff;
        color: rgb(70, 70, 70);
        text-align: center;
        margin: 0 auto;
        width: 80%;
        border-radius: 20px;
        line-height: 28px;
        box-sizing: border-box;
        line-height: 28px;
        border: 6px solid #fff;
        &:hover {
          background: #f4f9ff;
          color: var(--el-color-primary);
        }
      }
    }
    .onSelect {
      width: 25% !important;
      margin: 20px 0 !important;
      text-align: center;
      transition: all 0.3s ease-in-out;
      .selectOptions {
        cursor: pointer;
        height: 40px;
        background: var(--el-color-primary);
        color: #fff;
        text-align: center;
        margin: 0 auto;
        width: 80%;
        border-radius: 20px;
        line-height: 28px;
        border: 6px solid #f0f7ff;
        box-sizing: border-box;
        &:hover {
          // box-shadow: 0 0 4px var(--el-color-primary);
          transform: scale(1.02);
        }
      }
    }
    .columWidth {
      width: 33.33%;
    }
    .el-checkbox__input {
      display: none !important;
    }
    .el-checkbox__label {
      padding-left: 0px !important;
    }
  }
  .selectBox {
    width: 100px;

    input {
      height: 25px;
      line-height: 25px;
    }
    .el-input .el-input__icon {
      line-height: 25px;
    }
  }
  .tagStyle {
    margin-right: 10px;
    height: 25px;
    line-height: 25px;
  }
  .lableStyle {
    font-size: 14px;
  }
  .el-button--mini {
    padding: 5px 15px;
    font-size: 12px;
    border-radius: 3px;
  }
  .buttonBox {
    border-top: 1px solid #e5e5e5;
    padding: 10px 10px 10px 0;
    text-align: center;
    justify-content: flex-end;
    display: flex;
    // width: 100%;
    align-items: center;
  }
  .cursor {
    cursor: pointer;
  }
  .suffix {
    // background: #ffffff;
    margin-left: 10px;
    // position: absolute;
    // right: 10px;
    // top: 0;
    font-size: 12px;
    color: var(--el-color-primary);
  }
}

// 月份靠左
.monthLeft {
  justify-content: flex-start;
}
</style>
